import { useState, useEffect } from 'react';
import { Card, message, Typography, Divider, Space, Alert } from 'antd';
import { useNavigate, useLocation, Link } from 'react-router-dom';
import { GithubOutlined, WechatOutlined, QqOutlined, UserAddOutlined } from '@ant-design/icons';
import LoginForm from '../../components/login/LoginForm';
import authApi from '../../api/auth';
import './login.scss';

const { Title, Paragraph } = Typography;

const Login: React.FC = () => {
  const [loading, setLoading] = useState(false);
  const [loginError, setLoginError] = useState<string | null>(null);
  const navigate = useNavigate();
  const location = useLocation();
  const [bubbles, setBubbles] = useState<{ size: number; left: string; top: string; delay: number }[]>([]);

  // 在组件加载时检查是否已登录，如果已登录则重定向到欢迎页
  useEffect(() => {
    if (authApi.isAuthenticated()) {
      // 如果有重定向路径，使用该路径
      const { from } = (location.state as { from?: { pathname: string } }) || { from: { pathname: '/welcome' } };
      navigate(from.pathname || '/welcome');
    }
  }, [navigate, location]);

  useEffect(() => {
    // 创建随机气泡装饰元素
    const newBubbles = Array(8).fill(0).map(() => ({
      size: Math.random() * 100 + 50,
      left: `${Math.random() * 100}%`,
      top: `${Math.random() * 100}%`,
      delay: Math.random() * 2
    }));
    setBubbles(newBubbles);
  }, []);

  const onFinish = async (values: { username: string; password: string; remember: boolean; captcha?: string }) => {
    setLoading(true);
    setLoginError(null);
    try {
      // 使用API服务发送登录请求
      const response = await authApi.login({
        username: values.username,
        password: values.password,
        remember: values.remember,
        captcha: values.captcha
      });

      if (response.success && response.data) {
        message.success('登录成功！');

        // 如果有重定向路径，使用该路径
        const { from } = (location.state as { from?: { pathname: string } }) || { from: { pathname: '/welcome' } };
        navigate(from.pathname || '/welcome');
      } else {
        setLoginError(response.message || '登录失败，请检查用户名和密码');
        message.error(response.message || '登录失败');
      }
    } catch (error) {
      console.error('登录错误:', error);
      setLoginError('服务器连接异常，请稍后重试');
      message.error('登录过程中发生错误，请稍后重试');
    } finally {
      setLoading(false);
    }
  };

  // 根据气泡尺寸获取对应的类名
  const getBubbleSizeClass = (size: number) => {
    if (size < 70) return 'background-bubble--size-1';
    if (size < 100) return 'background-bubble--size-2';
    if (size < 130) return 'background-bubble--size-3';
    return 'background-bubble--size-4';
  };

  // 根据延迟获取对应的类名
  const getBubbleDelayClass = (delay: number) => {
    if (delay < 0.5) return 'background-bubble--delay-1';
    if (delay < 1) return 'background-bubble--delay-2';
    if (delay < 1.5) return 'background-bubble--delay-3';
    return 'background-bubble--delay-4';
  };

  // 检查URL中是否包含重定向提示
  const isRedirected = location.state && (location.state as any).from;

  return (
    <div className="login-container">
      {/* 添加背景装饰气泡 */}
      {bubbles.map((bubble, index) => (
        <div
          key={index}
          className={`background-bubble ${getBubbleSizeClass(bubble.size)} ${getBubbleDelayClass(bubble.delay)}`}
          style={{ left: bubble.left, top: bubble.top }}
        />
      ))}

      <Card className="login-card" bordered={false}>
        <div className="login-logo">
          <img src="https://gw.alipayobjects.com/zos/rmsportal/KDpgvguMpGfqaHPjicRK.svg" alt="Logo" />
        </div>

        <div className="login-header">
          <Title level={2}>企业后台管理系统</Title>
          <Paragraph>专业高效的管理系统解决方案</Paragraph>
        </div>

        {isRedirected && (
          <Alert
            message="请先登录"
            description="您需要登录后才能访问该页面"
            type="info"
            showIcon
            style={{ marginBottom: 20 }}
          />
        )}

        {loginError && (
          <Alert
            message="登录失败"
            description={loginError}
            type="error"
            showIcon
            closable
            style={{ marginBottom: 20 }}
            onClose={() => setLoginError(null)}
          />
        )}

        <LoginForm onFinish={onFinish} loading={loading} />

        <div className="register-link-section">
          <Link to="/register" className="register-link">
            <UserAddOutlined /> 没有账号？立即注册
          </Link>
        </div>

        <div className="social-login-section">
          <Divider plain>其他登录方式</Divider>
          <div className="social-icons">
            <GithubOutlined className="login-icon" title="Github登录" />
            <WechatOutlined className="login-icon" title="微信登录" />
            <QqOutlined className="login-icon" title="QQ登录" />
          </div>
        </div>

        <div className="login-footer">
          <Space split={<Divider type="vertical" />}>
            <a href="#">用户协议</a>
            <a href="#">隐私政策</a>
            <a href="#">帮助中心</a>
          </Space>
          <p>© {new Date().getFullYear()} 企业管理系统</p>
        </div>
      </Card>
    </div>
  );
};

export default Login; 